const core = require('@huaweicloud/huaweicloud-sdk-core');
const iotda = require("@huaweicloud/huaweicloud-sdk-iotda/v5/public-api");

// The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
// In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables HWCLOUD_AK and HWCLOUD_SK in the local environment
const ak = "PEITBGTHUZ7UWNOAOEVW";
const sk = "xtv9yZhechuRB2KaLLSYykqLV5bGLEx5eSML55cv";
const endpoint = "https://iotda.cn-north-4.myhuaweicloud.com";
const project_id = "05ebc154b3000f7c2f23c01945c65612";
// const securityToken = process.env.HWCLOUD_SECURITY_TOKEN;
const securityToken = "";
const credentials = new core.BasicCredentials()
  .withAk(ak)
  .withSk(sk)
    //  .withSecurityToken(securityToken) // Use in temporary aksk scene
  .withProjectId(project_id)
const client = iotda.IoTDAClient.newBuilder()
  .withCredential(credentials)
  .withEndpoint(endpoint)
  .build();

const request1 =  new iotda.ShowDeviceRequest();

let myHandler = async function (event, context, callback, logger) {
  logger.info('step1')
  logger.info(event);
  //app对接时取的是body的值，控制台测试时，没有body直接取值。此写法可以同时满足两种需求
  let deviceId=event.body?JSON.parse(event.body).deviceId:event.deviceId;
  logger.info("deviceId="+deviceId);
  // request1.deviceId = "delivery-drone-xdw_00001";
  request1.deviceId = deviceId;

  let result =  await client.showDevice(request1);
  logger.info('step2:'+JSON.stringify(result))
  let res = new context.HTTPResponse({"connStatus": result.status}, {
    "faas-content-type": "json"
  }, "application/json", "200");

  callback(res);

};

export { myHandler };